<?PHP
/*********************************************************************************
 * SugarCRM is a customer relationship management program developed by
 * SugarCRM, Inc. Copyright (C) 2004-2010 SugarCRM Inc.
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Affero General Public License along with
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 * 
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by SugarCRM".
 ********************************************************************************/
/**
 * THIS CLASS IS FOR DEVELOPERS TO MAKE CUSTOMIZATIONS IN
 */
require_once('modules/edanz_Editor/edanz_Editor_sugar.php');
class edanz_Editor extends edanz_Editor_sugar {

	var $table_name = "users";

	var $id;
 	var $user_name;
	var $first_name;
	var $last_name;
	var $reports_to_id;
	var $is_admin;
	var $external_auth_only;
	var $receive_notifications;
	var $description;
	var $date_entered;
	var $date_modified;
	var $modified_user_id;
	var $created_by;
	var $title;
	var $department;
	var $phone_home;
	var $phone_mobile;
	var $phone_work;
	var $phone_other;
	var $phone_fax;
	var $status;
	var $address_street;
	var $address_city;
	var $address_state;
	var $address_country;
	var $address_postalcode;
	var $deleted;
	var $portal_only;
	var $employee_status;
	var $messenger_id;
	var $messenger_type;
	var $is_group;
	var $editor_code;
	var $fish_test;
	var $salutation;
	var $bank_name;
	var $branch_name;
	var $bank_account_name;
	var $bank_account_number;
	var $branch_code;
	var $iban_number;
	var $swift_code;
	var $branch_address;
	var $branch_state;
	var $branch_postalcode;
	var $banking_country;
	var $bank_info_note;
	var $intermediary_bank_name;
	var $intermediary_bank_account_number;
	var $intermediary_bank_account_name;
	var $intermediary_bank_info_note;
	var $banking_currency;
	var $gender;
	var $edanz_start_date;


	
	function edanz_Editor(){	
		parent::edanz_Editor_sugar();
		$this->emailAddress = new SugarEmailAddress();
	}

        function save($check_notify = FALSE){
		//The pre_save code wasn't handling date field formats properly, so I'm re-setting those here before the save.
		require_once('include/SugarFields/SugarFieldHandler.php');
	        $sfh = new SugarFieldHandler();
                foreach($this->field_defs as $field => $properties) {
			if($properties['type'] == 'date'){	
				$sf = $sfh->getSugarField('date', true);
				if($sf != null){
					$sf->save($this, $_POST, $field, $properties);
				}
			}
		}


		// prevent notifications when saving the editor
                $id = parent::save(FALSE);
	        return $id;
        }

        function get_list_view_data(){

		global $current_user;
                $this->_create_proper_name_field(); // create proper NAME (by combining first + last)
                $user_fields = $this->get_list_view_array();
                // Copy over the reports_to_name
                if ( isset($GLOBALS['app_list_strings']['messenger_type_dom'][$this->messenger_type]) )
			$user_fields['MESSENGER_TYPE'] = $GLOBALS['app_list_strings']['messenger_type_dom'][$this->messenger_type];
                if ( isset($GLOBALS['app_list_strings']['employee_status_dom'][$this->employee_status]) )
			$user_fields['EMPLOYEE_STATUS'] = $GLOBALS['app_list_strings']['employee_status_dom'][$this->employee_status];
                $user_fields['REPORTS_TO_NAME'] = $this->reports_to_name;
                $user_fields['NAME'] = empty($this->name) ? '' : $this->name;
                $user_fields['EMAIL1'] = $this->emailAddress->getPrimaryAddress($this,$this->id,'Users');
                $this->email1 = $user_fields['EMAIL1'];
		$user_fields['EMAIL1_LINK'] = $current_user->getEmailLink('email1', $this, '', '', 'ListView');
		$user_fields['EDITOR_CODE'] = $this->banking_country.str_pad($this->editor_number, 3, '0', STR_PAD_LEFT);
		$user_fields['LBL_VIEW_SCHEDULE'] = translate('LBL_VIEW_SCHEDULE', 'edanz_Editor');
                return $user_fields;
        }

        /**
         * Generate the name field from the first_name and last_name fields.
         */
        function _create_proper_name_field() {
		global $locale;
		$full_name = $locale->getLocaleFormattedName($this->first_name, $this->last_name);
		$this->name = $full_name;
		$this->full_name = $full_name;
        }

	//this function was taken from include/utils.php, and modified to ignore the earb.bean_module because the bean module might be edanz_Editor or Users
	function get_email_query($type) {
	    global $current_user;

	    $return_array['select']='SELECT emails.id ';
	    $return_array['from']='FROM emails ';
	    $return_array['where']="";
		$return_array['join'] = " JOIN (select DISTINCT email_id from emails_email_addr_rel eear

		join email_addr_bean_rel eabr on eabr.bean_id ='$this->id' and
		eabr.email_address_id = eear.email_address_id and eabr.deleted=0
		where eear.deleted=0
		) derivedemails on derivedemails.email_id = emails.id";
	    $return_array['join_tables'][0] = '';

		if (isset($type) and isset($type['return_as_array']) and $type['return_as_array']==true) {
			return $return_array;
		}

		return $return_array['select'] . $return_array['from'] . $return_array['where'];
	}

	function fill_in_additional_detail_fields() {
		parent::fill_in_additional_detail_fields();
		require_once('modules/edanz_Schedule/EditorLoad.php');
		$this->completion_punctuality = get_punctuality($this->id);
/*
		// This causes an infinite loop of retrieves. don't do it!!!
		$feedback_items = $this->get_linked_beans('feedback', 'edanz_Feedback');
		$rating_sum = 0;
$GLOBALS['log']->fatal("feedback: ".print_r($feedback_items, true));
		foreach($feedback_items as $feedback){
			$rating_sum += $feedback->quality_rating;
		}
		if(!empty($feedback_items)){
			$this->average_quality_rating = round($rating_sum/count($feedback_items), 2);
		}
*/
$query = "(select sum(ratingTable.rating ) rating_sum,count(ratingTable.rating) as items, 'ten' as type from (SELECT 
                       quality_rating as rating
                FROM edanz_feedback
                WHERE quality_rating IS NOT NULL
                AND related_editor_id = '".$this->id."'
                AND deleted = 0
                AND name = 'Assignment' order by date_entered desc LIMIT 0,10) ratingTable)

union all

(select sum(ratingTable.rating ) rating_sum,count(ratingTable.rating) as items , 'three' as type from (SELECT 
                       quality_rating as rating
                FROM edanz_feedback
                WHERE quality_rating IS NOT NULL
                AND related_editor_id = '".$this->id."'
                AND deleted = 0
                AND name = 'Assignment' order by date_entered desc LIMIT 0,3) ratingTable)

union

(select sum(ratingTable.rating ) rating_sum,count(ratingTable.rating) as items , 'all' as type from (SELECT 
                       quality_rating as rating
                FROM edanz_feedback
                WHERE quality_rating IS NOT NULL
                AND related_editor_id = '".$this->id."'
                AND deleted = 0
                AND name = 'Assignment' order by date_entered desc) ratingTable)";

		$result = $this->db->query($query,true," Error filling in additional detail fields: ");

unset($this->average_quality_rating);
unset($this->ten_quality_rating);
unset($this->three_quality_rating);

		while($row = $this->db->fetchByAssoc($result))
{
		if($row != null && $row['items'] > 0)
		{
                     if($row['type'] == 'all')
                      {if($row['items'] > 10)
			$this->average_quality_rating = round($row['rating_sum']/$row['items'], 2);}
                     else if($row['type'] == 'ten')
                      {if($row['items'] > 3)
	  		$this->ten_quality_rating = round($row['rating_sum']/$row['items'], 2);	}
                     else if($row['type'] == 'three'){
		        $this->three_quality_rating = round($row['rating_sum']/$row['items'], 2);
			}
		}
	}
}
	function isNewEditor(){
		$query = "SELECT SUM(Tasks) As TotalTasks
			FROM (
				SELECT COUNT(*) AS Tasks
				FROM tasks
				WHERE status = 'Completed'
					AND type = 'FirstEdit'
					AND assigned_user_id = '".$this->id."'
					AND deleted = 0

				UNION

				SELECT IFNULL(historic_task_totals.task_count, 0) AS Tasks
				FROM historic_task_totals
				WHERE task_type = 'FirstEdit'
					AND user_id = '".$this->id."'
			) As CountedPlusHistoric";
		$result = $this->db->query($query,true," Error getting edit count: ");

	        $row = $this->db->fetchByAssoc($result);
	        if($row != null){
			return $row['TotalTasks'] < 3;
		}else{
			return true;
		}
	}

	function isOnProbation(){
		$where_clause = array();
		$where_clause['lhs_field'] = 'status';
		$where_clause['operator'] = '=';
		$where_clause['rhs_value'] = 'Active';
		$probation = $this->get_linked_beans('probation', 'edanz_Probation', array(), 0, -1, 0, $where_clause);
		return count($probation) > 0;
	}
        function process_list_query($query, $row_offset, $limit= -1, $max_per_page = -1, $where = '')
        {
                $query = str_replace('jt0.assigned_user_id= users.id','users.assigned_user_id=jt0.id',$query);
                $query = str_replace('users.status'," users.is_group='0' and users.employee_status",$query);
                return parent::process_list_query($query, $row_offset, $limit, $max_per_page, $where);
        }
}

function get_employee_status_array(){
        global $app_list_strings;
        return $app_list_strings['employee_status_dom'];
}

//taken from the EmployeeStatus.php. The Editor has its own permissions so we don't want to restrict the employee status to admins.
function customGetEmployeeStatusOptions($focus, $name = 'employee_status', $value, $view = 'DetailView') {
        global $current_user, $app_list_strings;
    if($view == 'EditView' || $view == 'MassUpdate') {

//           if (is_admin($current_user)) {
            $employee_status  = "<select name='$name'";
                        if(!empty($sugar_config['default_user_name'])
                           && $sugar_config['default_user_name'] == $focus->user_name
                           && isset($sugar_config['lock_default_user_name'])
                           && $sugar_config['lock_default_user_name'])
                    {
                                $employee_status .= " disabled ";
                        }
                        $employee_status .= ">";
                        $employee_status .= get_select_options_with_id($app_list_strings['employee_status_dom'], $focus->employee_status);
                        $employee_status .= "</select>\n";
/*           } else {
                    $employee_status = '';
           }
*/
           return $employee_status;
        } //if($view == 'EditView')

    if ( isset($app_list_strings['employee_status_dom'][$focus->employee_status]) )
        return $app_list_strings['employee_status_dom'][$focus->employee_status];

        return $focus->employee_status;
}

?>
